import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import websocket from '@/utils/websocket'
import { getUserInfo } from '@/utils/index'
import NotificationService from '@/utils/notification'

/**
 * WebSocket私聊消息状态管理
 * 管理私聊相关的消息状态
 */
export const usePrivateChatStore = defineStore('privateChat', () => {
  // 私聊消息映射，按聊天ID分组
  const privateChats = ref(new Map())
  
  // 未读消息数
  const privateUnreadCount = ref(0)
  
  // 添加私聊消息（带去重）
  const addPrivateMessageUnique = (chatId, message) => {
    // 确保chatId存在
    if (!privateChats.value.has(chatId)) {
      privateChats.value.set(chatId, [])
    }
    
    const messages = privateChats.value.get(chatId)
    
    // 检查消息是否已存在
    const exists = messages.some(msg => msg.message_id === message.message_id)
    
    // 如果消息不存在，则添加
    if (!exists) {
      messages.push({
        ...message
      })
    }
    
    // 更新未读消息数
    updateUnreadCount()
  }
  
  // 设置私聊消息（替换整个聊天记录）
  const setPrivateMessages = (chatId, messages) => {
    privateChats.value.set(chatId, messages.map(msg => ({
      ...msg
    })))
  }
  
  // 获取特定聊天的所有消息
  const getPrivateMessages = (chatId) => {
    return privateChats.value.get(chatId) || []
  }
  
  // 清空所有私聊消息数据
  const clearPrivateChats = () => {
    privateChats.value.clear()
    privateUnreadCount.value = 0
  }
  
  // 更新未读消息数
  const updateUnreadCount = () => {
    // 获取当前用户ID
    const userInfo = uni.getStorageSync('userInfo')
    const currentUserId = userInfo ? userInfo.user_id : null
    
    // 计算所有未读消息数
    let count = 0
    for (const [chatId, messages] of privateChats.value.entries()) {
      const chatUnreadCount = messages.filter(msg => 
        msg.receiver_id === currentUserId && // 只统计发送给当前用户的消息
        msg.status !== 'read' // 状态不是已读
      ).length
      count += chatUnreadCount
    }
    
    privateUnreadCount.value = count
    
    // 触发事件，让自定义tabBar组件更新徽标
    uni.$emit('updateUnreadCount', count)
  }

  // 发送私聊消息
  const handlePrivateMessageSend = (data) => {
    try {
      const messageData = {
        type: 'private_message',
        msg: '发送消息',
        receiverId: null,
        content: ''
      }
      Object.assign(messageData, data)
      // 发送消息
      websocket.sendMessage(messageData)
    } catch (error) {
      console.error('发送消息时出错:', error)
    }
  }

  // 处理 发送 私聊消息成功的响应
  const handlePrivateMessageSendSuccess = (data) => {
    // 确保chatId存在
    if (!privateChats.value.has(data.chat_id)) {
      privateChats.value.set(data.chat_id, []);
    }
    addPrivateMessageUnique(data.chat_id, data);
  }
  
  // 处理 接收 到私聊消息
  const handlePrivateMessageReceived = (data) => {
    // 确保chatId存在
    if (!privateChats.value.has(data.chat_id)) {
      privateChats.value.set(data.chat_id, []);
    }
    addPrivateMessageUnique(data.chat_id, data);
    
    // 触发设备提醒（震动和声音）
    // NotificationService.triggerNotification({
    //   vibrate: true,
    //   sound: true,
    //   senderId: data.sender_id
    // });
    
    // 在App平台上创建系统通知栏消息
    // #ifdef APP-PLUS
    NotificationService.showSystemNotification(data, 'private_message');
    // #endif
  }

  // 标记私聊为已读
  const markPrivateChatAsRead = (chatId) => {
    // 获取当前用户信息
    const userInfo = getUserInfo()

    try {
      // 只处理指定chatId的聊天消息
      if (privateChats.value && privateChats.value.has(chatId)) {
        const messages = privateChats.value.get(chatId);
        for (const message of messages) {
          // 只标记发送给当前用户且未读的消息
          if (message.status !== 'read' && message.receiver_id === userInfo.user_id) {
            const readData = {
              type: 'private_message_read',
              messageId: message.message_id
            };
            websocket.sendMessage(readData);
          }
        }
      }
    } catch (error) {
      console.error('处理消息已读状态时出错:', error)
    }
  }
  
  // 处理私聊消息已读成功的响应
  const handlePrivateMessageReadSuccess = (messageId) => {
    try {
      if (privateChats.value && typeof privateChats.value.entries === 'function') {
        for (const [chatId, messages] of privateChats.value.entries()) {
          const message = messages.find(msg => msg.message_id === messageId)
          if (message) {
            message.status = 'read'
            break
          }
        }
      }

      updateUnreadCount()
    } catch (error) {
      console.error('处理消息已读状态时出错:', error)
    }
  }

  return {
    // 状态
    privateChats,
    privateUnreadCount,

    // 方法
    addPrivateMessageUnique,
    setPrivateMessages,
    getPrivateMessages,
    clearPrivateChats,
    handlePrivateMessageSend,
    handlePrivateMessageSendSuccess,
    handlePrivateMessageReceived,
    markPrivateChatAsRead,
    handlePrivateMessageReadSuccess
  }
})